<template>
  <el-dialog
    :title="title"
    v-model="visible"
    :close-on-click-modal="false"
    :close-on-press-escape="true"
    :show-close="true"
    class="resizable-dialog"
    width="60%"
    @close="handleDialogClose"
  >
    <div class="dialog-content">
      <el-steps :active="currentStep" finish-status="success" class="steps-container">
        <el-step title="准备中"></el-step>
        <el-step title="克隆代码"></el-step>
        <el-step title="安装依赖"></el-step>
        <el-step title="构建"></el-step>
        <el-step title="发布"></el-step>
      </el-steps>
      
      <div class="progress-log-container">
        <pre v-html="formattedLog" class="log-content"></pre>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose" type="danger">
          {{ isRunning ? '中断' : '关闭' }}
        </el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 添加确认对话框 -->
  <el-dialog
    v-model="confirmDialogVisible"
    title="确认"
    width="30%"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :show-close="false"
  >
    <span>{{ confirmMessage }}</span>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleConfirm(false)">取消</el-button>
        <el-button type="primary" @click="handleConfirm(true)">确认</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 添加密码输入对话框 -->
  <el-dialog
    v-model="passwordDialogVisible"
    title="输入发布密码"
    width="30%"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :show-close="false"
  >
    <el-form :model="passwordForm">
      <el-form-item label="发布密码">
        <el-input
          v-model="passwordForm.password"
          type="password"
          placeholder="请输入发布密码"
          show-password
          @keyup.enter="handlePasswordConfirm(true)"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handlePasswordConfirm(false)">取消</el-button>
        <el-button type="primary" @click="handlePasswordConfirm(true)">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { wsConfig } from '../api'

export default {
  name: 'PublishProgress',
  props: {
    // 添加属性以支持多窗口
    dialogId: {
      type: String,
      required: true
    },
    owner: {
      type: String,
      required: true
    },
    name: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      visible: false,
      currentStep: 0,
      currentLog: '',
      isRunning: false,
      timeout: 0,
      ws: null,
      confirmDialogVisible: false,
      confirmMessage: '',
      confirmResolve: null,
      passwordDialogVisible: false,
      passwordForm: {
        password: ''
      },
      passwordResolve: null
    }
  },
  computed: {
    title() {
      return `发布进度 - ${this.owner}/${this.name}`
    },
    formattedLog() {
      // 将日志中的错误信息标红
      return this.currentLog.replace(
        /(ERROR|失败|FAILED)/g, 
        '<span style="color: red">$1</span>'
      );
    }
  },
  methods: {
    show() {
      this.visible = true
      this.isRunning = true
      this.currentStep = 0
      this.currentLog = ''
      this.connectWebSocket()
    },
    handleDialogClose() {
      if (this.isRunning) {
        this.$confirm('确定要中断当前执行过程吗？', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.handleInterrupt()
        }).catch(() => {})
      } else {
        this.hide()
        this.$emit('close', this.dialogId)
      }
    },
    handleClose() {
      this.handleDialogClose()
    },
    handleInterrupt() {
      if (this.ws && this.ws.readyState === WebSocket.OPEN) {
        this.ws.send(JSON.stringify({
          type: 'interrupt',
          message: '用户中断执行'
        }))
      }
      this.disconnectWebSocket()
      this.hide()
      this.$emit('close', this.dialogId)
    },
    hide() {
      this.visible = false
      this.isRunning = false
      this.disconnectWebSocket()
    },
    connectWebSocket() {
      this.ws = new WebSocket(wsConfig.publishEndpoint)
      
      this.ws.onmessage = (event) => {
        const data = JSON.parse(event.data)
        if (data.type === 'progress') {
          this.updateProgress(data.status, data.message)
        } else if (data.type === 'confirm') {
          this.handleConfirmation(data.message)
        }
      }

      this.ws.onclose = () => {
        console.log('WebSocket 连接已关闭')
        // 可以在这里添加重连逻辑
      }

      this.ws.onerror = (error) => {
        console.error('WebSocket 错误:', error)
      }
    },
    disconnectWebSocket() {
      if (this.ws) {
        this.ws.close()
        this.ws = null
      }
    },
    // 添加确认方法
    async handleConfirmation(message) {
      if (message.includes('请输入发布密码')) {
        this.passwordDialogVisible = true
        try {
          const confirmed = await new Promise(resolve => {
            this.passwordResolve = resolve
          })
          
          if (confirmed && this.ws && this.ws.readyState === WebSocket.OPEN) {
            this.ws.send(JSON.stringify({
              type: 'confirmation',
              result: true,
              password: this.passwordForm.password
            }))
          } else {
            this.ws.send(JSON.stringify({
              type: 'confirmation',
              result: false
            }))
          }
        } finally {
          this.passwordDialogVisible = false
          this.passwordForm.password = ''
        }
      } else {
        try {
          const confirmed = await this.$confirm(message, '确认', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
          
          // 发送确认结果回服务器
          if (this.ws && this.ws.readyState === WebSocket.OPEN) {
            this.ws.send(JSON.stringify({
              type: 'confirmation',
              result: confirmed === 'confirm'
            }))
          }
        } catch (error) {
          // 用户取消确认
          if (this.ws && this.ws.readyState === WebSocket.OPEN) {
            this.ws.send(JSON.stringify({
              type: 'confirmation',
              result: false
            }))
          }
        }
      }
    },
    async onConfirmation(message) {
      this.confirmMessage = message
      this.confirmDialogVisible = true
      
      // 返回Promise以等待用户确认
      return new Promise(resolve => {
        this.confirmResolve = resolve
      })
    },
    // 处理用户确认结果
    handleConfirm(confirmed) {
      this.confirmDialogVisible = false
      if (this.confirmResolve) {
        this.confirmResolve(confirmed)
        this.confirmResolve = null
      }
    },
    updateProgress(status, message) {
      // 添加时间戳
      const now = new Date().toLocaleString()
      this.currentLog += `[${now}] ${message}\n`
      
      // 自动滚动到底部
      this.$nextTick(() => {
        const logElement = this.$el.querySelector('.progress-log')
        if (logElement) {
          logElement.scrollTop = logElement.scrollHeight
        }
      })

      // 更新进度状态
      if (status) {
        switch(status) {
          case 'PREPARING': this.currentStep = 1; break;
          case 'CLONING': this.currentStep = 2; break;
          case 'INSTALLING': this.currentStep = 3; break;
          case 'BUILDING': this.currentStep = 4; break;
          case 'PUBLISHING': this.currentStep = 5; break;
          case 'COMPLETED':
            this.currentStep = 5;
            this.isRunning = false;
            break;
          case 'FAILED':
            this.isRunning = false;
            break;
        }
      }
    },
    handleClose() {
      if (this.isRunning) {
        // 显示确认对话框
        this.$confirm('确定要中断当前执行过程吗？', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // 用户确认中断
          if (this.ws && this.ws.readyState === WebSocket.OPEN) {
            this.ws.send(JSON.stringify({
              type: 'interrupt',
              message: '用户中断执行'
            }))
          }
          this.disconnectWebSocket()
          this.visible = false
          this.isRunning = false
        }).catch(() => {
          // 用户取消中断，不做任何操作
        })
      } else {
        this.visible = false
      }
    }
  }
}
</script>

<style scoped>
/* 对话框基础样式 */
:deep(.el-dialog) {
  position: absolute;
  margin: 0 !important;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  min-width: 600px;
  min-height: 400px;
  resize: both;
  overflow: visible !important;
}

:deep(.el-dialog__body) {
  height: calc(100% - 110px); /* 减去header和footer的高度 */
  padding: 10px;
  overflow: hidden;
}

/* 内容区域布局 */
.dialog-content {
  display: flex;
  flex-direction: column;
  height: 100%;
  gap: 20px;
}

/* 步骤条容器 */
.steps-container {
  flex-shrink: 0;
  padding: 10px 0;
}

/* 日志区域容器 */
.progress-log-container {
  flex: 1;
  min-height: 200px;
  background: #f5f5f5;
  border-radius: 4px;
  overflow: auto;
  position: relative;
}

/* 日志内容样式 */
.log-content {
  margin: 0;
  padding: 10px;
  font-family: monospace;
  white-space: pre-wrap;
  word-wrap: break-word;
}

/* 拖动手柄样式 */
:deep(.el-dialog):after {
  content: '';
  position: absolute;
  bottom: 0;
  right: 0;
  width: 20px;
  height: 20px;
  cursor: se-resize;
  background: linear-gradient(135deg, transparent 50%, #e4e7ed 50%, #e4e7ed 100%);
}

/* 对话框头部和底部样式 */
:deep(.el-dialog__header) {
  cursor: move;
  padding: 15px;
  margin: 0;
}

:deep(.el-dialog__footer) {
  padding: 10px;
  border-top: 1px solid #dcdfe6;
}

/* 自定义滚动条样式 */
.progress-log-container::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

.progress-log-container::-webkit-scrollbar-thumb {
  background: #c0c4cc;
  border-radius: 4px;
}

.progress-log-container::-webkit-scrollbar-track {
  background: #f5f5f5;
}
</style>